package com.unitd.modules.configcenter.controller;

import com.unitd.frame.springweb.controller.result.AjaxResult;
import com.unitd.modules.comm.web.BaseController;
import com.unitd.modules.configcenter.component.ConfigStateHolder;
import com.unitd.modules.sso.util.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @author Hudan
 * @version 1.0
 * @desc 配置中心应用信息监控管理前端控制器
 * @filename MonitorController.java
 * @copyright www.unitd.com
 * @date 2018/1/31
 */
@RestController
@RequestMapping("/monitor/app")
public class MonitorController extends BaseController {

	@Autowired
	private ConfigStateHolder configStateHolder;

	/**
	 * @desc 获取指定环境下有效的处于激活状态的客户端
	 * @param env 环境
	 * @return 自定义的通用json对象
	 */
	@RequestMapping(value = "{env}", method = RequestMethod.GET)
	public AjaxResult getActiveAppNodes(@PathVariable("env") String env) {
		SecurityUtil.requireProfileGanted(env);
		List<ConfigStateHolder.ConfigState> list = configStateHolder.get(env);
		return new AjaxResult(list);
	}

	/**
	 * @desc 获取指定环境下,指定应用的配置属性信息
	 * @param env 指定的环境
	 * @param appName 指定的应用名称
	 * @param nodeId 指定节点
	 * @return 自定义的通用json对象
	 */
	@RequestMapping(value = "config/{env}/{appName}", method = RequestMethod.GET)
	public AjaxResult getNodeConfig(@PathVariable("env") String env, @PathVariable("appName") String appName, @RequestParam("nodeId") String nodeId) {
		SecurityUtil.requireProfileGanted(env);
		StringBuilder content = new StringBuilder();
		List<ConfigStateHolder.ConfigState> list = configStateHolder.get(appName, env);
		for (ConfigStateHolder.ConfigState configState : list) {
			if (configState.getNodeId().equals(nodeId)) {
				Map<String, String> configs = configState.getConfigs();
				for (String key : configs.keySet()) {
					content.append(key).append(" = ").append(configs.get(key)).append("<br>");
				}
				break;
			}
		}
		return new AjaxResult(content);
	}
}